#include "key.h"
#include "work.h"
#include "iap.h"

uint8_t k1_cnt=0,k2_cnt=0,touch_cnt,boot_cnt=0,life_cnt=0,age_cnt=0;
boolean_t Touch_OK=0;//Continuous_Mode=0;
uint8_t k1_time=0,k1_cnt1=0,k3_cnt=0;
extern uint16_t off_cnt1,period_cnt;
extern uint8_t Work_Mode,Work_Strength,period_cnt1,Ems_Duty;
extern uint8_t ms10_cnt,flash_cnt,Beep_Time,phase_cnt;
extern boolean_t Voltage_OK,Trigger_Continuous,efficiency_error;
extern boolean_t Change_f,Fan_Error,Temp_Error,ems_f;
extern boolean_t age_mode,life_mode,flash_f,uvp_f;
extern uint8_t bat_low_flag;
extern uint16_t err_to_sleep_cnt;
extern float BAT_Voltage;
extern uint8_t off_cnt2;
extern uint16_t sleep_cnt;

// extern boolean_t Boot_Mode;

void Key_Scan()
{

// ---档位 + 按键
	if(K1==0){
		if(k1_cnt < 250){
			k1_cnt++;
		}	
	}
	else{
		if((k1_cnt > 3) && (k1_cnt <= 100)){
			printf(" level --\r\n");
			if(Work_Mode){
				if(Work_Strength){
					Work_Strength--;
					flash_cnt = 0;
					flash_f = 1;
					Beep_Time = 1;
				}
//				if(Work_Strength==0){
//					period_cnt=0;
//					period_cnt1=0;
//					phase_cnt=0;
//					ems_f=0;
//				}
			}
		}
		k1_cnt = 0;
		if(age_cnt < 250){
			age_cnt++;
		}	
	}
// --- 开关机 按键	
	if(K2 == 0){
		if(k2_cnt < 250){
			k2_cnt++;
		}
		if(k2_cnt == 150){
			if(0 == USB_IN){
				err_to_sleep_cnt = 0;
				bat_low_flag = 0;
				if(Work_Mode){	// 长按按键，触发关机
					Work_Mode = 0;
					Beep_Time = 3;
				}
				else{			// 长按按键，触发开机
//					printf("V0.0.5, long_key_wake\r\n");
//					printf("BAT_Voltage:[%d]\r\n", BAT_Voltage);
					if(BAT_Voltage < 3.4f){
						bat_low_flag = 1;  // 低电量 进入err提示
						Work_Mode = ERR_MODE;
					}
					else{
						Work_Mode = 1;
						Beep_Time = 3;
						flash_cnt = 0;
						flash_f = 0;
					}
					
				}
				off_cnt1 = 0;
				off_cnt2 = 0;
				Work_Strength = 0;
				sleep_cnt = 0;
			}
		}
	}
	else{
		if((k2_cnt > 3) && (k2_cnt <= 100)){
			printf(" power key\r\n");
			if(Work_Mode){
				Work_Mode++;
				if(Work_Mode > 4){
					Work_Mode = 1;
				}
				
				Ems_Duty = 0;
				Work_Strength = 0;
				off_cnt1 = 0;
				off_cnt2 = 0;
				Beep_Time = 1;
				period_cnt = 0;
				period_cnt1 = 0;
				phase_cnt = 0;
				ems_f = 0;
				GPIO_PB04_AF_GPIO_SET();
				GPIO_PB01_AF_GPIO_SET();
			}
			else{
				if(k1_cnt == 250){
					boot_cnt++;
				}
				else{
					boot_cnt = 0;
				}
				if(boot_cnt > 10){
						// Boot_Mode=1;
					Work_Mode=0;
				}
			}
		}
		k2_cnt = 0;
		if(life_cnt < 250){
			life_cnt ++;
		}
	}
// --- 档位- 按键		
	if(K3 == 0){
		if(k3_cnt < 250){
			k3_cnt++;
		}
		
	}
	else{
		if((k3_cnt > 3) && (k3_cnt < 100)){
			printf(" level ++\r\n");
			if(Work_Mode){
				if(Work_Strength < 7)
				{
					Work_Strength++;
					Beep_Time = 1;
					flash_cnt = 0;
					flash_f = 0;
//					period_cnt=0;
//					period_cnt1=0;
//					phase_cnt=0;
//					ems_f=0;
				}
			}
		}
		k3_cnt = 0;
	}
}

